import Phaser from 'phaser';
import PlayerSprite from '../sprites/PlayerSprite';
import skyPng from '../assets/images/sky.png';
import groundPng from '../assets/images/platform.png';
import starPng from '../assets/images/star.png';
import bombPng from '../assets/images/bomb.png';
import dudePng from '../assets/images/dude.png';

export default class GameScene extends Phaser.Scene {
  player!: PlayerSprite;

  platforms!: Phaser.Physics.Arcade.StaticGroup;

  score: number;

  scoreText!: Phaser.GameObjects.Text;

  stars!: Phaser.Physics.Arcade.Group;

  bombs!: Phaser.Physics.Arcade.Group;

  constructor() {
    super({ key: 'game' });
    this.score = 0;
  }

  preload() {
    this.load.image('sky', skyPng);
    this.load.image('ground', groundPng);
    this.load.image('star', starPng);
    this.load.image('bomb', bombPng);
    this.load.spritesheet('dude', dudePng, { frameWidth: 32, frameHeight: 48 });
  }

  create() {
    this.addSky();
    this.addPlatforms();
    this.addStars();
    this.addScore();
    this.addBombs();
    this.addPlayer();
  }

  addSky() {
    this.add.image(400, 300, 'sky');
  }

  addPlatforms() {
    this.platforms = this.physics.add.staticGroup();
    this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
    this.platforms.create(600, 400, 'ground');
    this.platforms.create(50, 250, 'ground');
    this.platforms.create(750, 220, 'ground');
  }

  addStars() {
    this.stars = this.physics.add.group({ key: 'star', repeat: 11, setXY: { x: 12, y: 0, stepX: 70 } });
    this.stars.children.iterate((child: any) => child.setBounceY(Phaser.Math.FloatBetween(0.4, 0.8)));
    this.physics.add.collider(this.stars, this.platforms);
  }

  addScore() {
    this.scoreText = this.add.text(16, 16, 'score: 0', { fontSize: '32px', backgroundColor: '#000' });
  }

  addBombs() {
    this.bombs = this.physics.add.group();
    this.physics.add.collider(this.bombs, this.platforms);
  }

  addPlayer() {
    this.player = new PlayerSprite(this, 100, 450, 'dude');

    this.physics.add.collider(this.player, this.platforms);
    this.physics.add.overlap(this.player, this.stars, (p: any, s: any) => {
      s.disableBody(true, true);

      this.score += 10;
      this.scoreText.setText(`score: ${this.score}`);

      if (this.stars.countActive(true) === 0) {
        this.stars.children.iterate((child: any) => child.enableBody(true, child.x, 0, true, true));
      }
      const x = p.x < 400 ? Phaser.Math.Between(400, 800) : Phaser.Math.Between(0, 400);
      const bomb = this.bombs.create(x, 16, 'bomb');
      bomb.setBounce(1);
      bomb.setCollideWorldBounds(true);
      bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
    }, undefined, this);
    this.physics.add.collider(this.player, this.bombs, (p: any) => {
      this.physics.pause();
      p.setTint(0xff0000);
      p.anims.play('turn');
    });
  }
}
